package com.tpfinal.agenda.core.mysqlrequests;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.tpfinal.agenda.controller.MainController;
import com.tpfinal.agenda.core.AgendaActionParamsCodes;
import com.tpfinal.agenda.core.AgendaActionsIDs;
import com.tpfinal.agenda.model.Company;
import com.tpfinal.agenda.model.Contact;
import com.tpfinal.agenda.model.Person;

public class InsertContactRequest extends MySqlBaseRequest {

	private static final String QUERY = "INSERT INTO contactos (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) VALUES ('%s','%s','%s',%s,%s,'%s',%s,%s,'%s','%s')";
	private Contact contact;

	@Override
	public int getID() {
		return AgendaActionsIDs.INSTERT_CONTACT;
	}

	@Override
	protected void setup(Map<String, Object> params) {

		this.queryType = QUERY_TYPE_UPDATE;

		contact = (Contact) params.get(AgendaActionParamsCodes.PARAM_CONTACT);

		String type = null;
		String name = contact.getName();
		String address = contact.getAddress();
		int zip = contact.getCityInfo().getZip();
		int phone = contact.getPhone();
		String email = contact.getEmail();
		String birthday = null;
		int cellphone = 0;
		String url = null;
		String businessSector = null;

		if (contact instanceof Person) {
			type = MySQL.MYSQL_CONTACT_TYPE_PERSON;
			birthday = String.format("'%s'",
					((Person) contact).getBirthdayAsString());
			cellphone = ((Person) contact).getCellphone();
		} else {
			type = MySQL.MYSQL_CONTACT_TYPE_COMPANY;
			url = ((Company) contact).getUrl();
			businessSector = ((Company) contact).getBusinessSector();
		}

		this.sqlQuery = String.format(QUERY, MySQL.MYSQL_COLUMN_TIPO,
				MySQL.MYSQL_COLUMN_NOMBRE_RAZON, MySQL.MYSQL_COLUMN_DIRECCION,
				MySQL.MYSQL_COLUMN_CP, MySQL.MYSQL_COLUMN_TELEFONO,
				MySQL.MYSQL_COLUMN_EMAIL, MySQL.MYSQL_COLUMN_TELEFONO_MOVIL,
				MySQL.MYSQL_COLUMN_FECHA_NACIMIENTO, MySQL.MYSQL_COLUMN_WEB,
				MySQL.MYSQL_COLUMN_RUBROS, type, name, address, zip, phone,
				email, cellphone, birthday, url, businessSector);

		System.out.println(this.sqlQuery);
	}

	@Override
	protected Map<String, Object> processResult(Map<String, Object> resultSet) {

		try {

			ResultSet generatedKeys = (ResultSet) resultSet
					.get(MySqlBaseRequest.MYSQL_RESULTSET);

			if (generatedKeys.next()) {
				contact.setId(generatedKeys.getInt(1));
			}

			MainController controller = MainController.get();
			controller.getContactsList().add(contact);
			controller.setSelectedContact(contact);

			connection.close();
			resultSet.put(RESULT_CODE, OK);
		} catch (SQLException e) {
			e.printStackTrace();
			resultSet.put(RESULT_CODE, ERROR);
		}

		return resultSet;
	}

}
